<template>
  <div class="manager-way-detail">
    <TitleBar title="基本信息" />
    <el-form v-if="type !== 'view'" ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="管理办法名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" clearable :maxlength="50" show-word-limit
          style="width: 400px;" />
      </el-form-item>
      <el-form-item label="文号" prop="documentName">
        <el-input v-model="form.documentName" placeholder="请输入" clearable :maxlength="50" show-word-limit
          style="width: 400px;" />
      </el-form-item>
      <el-form-item label="开始生效时间" prop="effectiveTime">
        <el-date-picker v-model="form.effectiveTime" type="date" placeholder="请选择" clearable style="width: 400px;" />
      </el-form-item>
      <el-form-item label="科研分酬金标准" prop="remuneration">
        <div class="flex space-x-[8px]">
          <span>按照</span>
          <el-input-number v-model="form.remuneration" placeholder="请输入" :controls="false" :precision="0" :min="0" />
          <span>元/分，发放科研酬金</span>
        </div>
        <!-- <div v-else>按照{{ form.remuneration }}元/分，发放科研酬金</div> -->
      </el-form-item>
      <el-form-item label="管理文件" prop="files">
        <FileUpload v-model="form.files" :limit="20" :fileType="[]" :is-show-tip="false" width="400px" />
      </el-form-item>
    </el-form>
    <div v-else class="mb-[24px] border-[1px] border-[#BEDAFF]">
      <div class="flex border-b-[1px] border-[#BEDAFF]">
        <div class="flex-1 flex items-center border-r-[1px] border-[#BEDAFF]">
          <div class="flex items-center w-[131px] h-full px-[16px] text-[#4E5969] bg-[#F6FAFF] border-r-[1px] border-[#BEDAFF]">管理办法名称
          </div>
          <div class="flex-1 px-[16px] py-[14px] leading-[22px]">{{ form.name }}</div>
        </div>
        <div class="flex-1 flex items-center">
          <div class="flex items-center w-[131px] h-full px-[16px] text-[#4E5969] bg-[#F6FAFF] border-r-[1px] border-[#BEDAFF]">文号
          </div>
          <div class="flex-1 px-[16px] py-[14px] leading-[22px]">{{ form.documentName }}</div>
        </div>
      </div>
      <div class="flex border-b-[1px] border-[#BEDAFF]">
        <div class="flex-1 flex items-center">
          <div class="flex items-center w-[131px] h-full px-[16px] text-[#4E5969] bg-[#F6FAFF] border-r-[1px] border-[#BEDAFF]">开始生效时间
          </div>
          <div class="flex-1 py-[14px] px-[16px] text-[#F53F3F]">{{
            formateDate(form.effectiveTime).format('YYYY-MM-DD')
            }}</div>
        </div>
      </div>
      <div class="flex border-b-[1px] border-[#BEDAFF]">
        <div class="flex-1 flex items-center">
          <div class="flex items-center w-[131px] h-full px-[16px] text-[#4E5969] bg-[#F6FAFF] border-r-[1px] border-[#BEDAFF]">科研分酬金标准
          </div>
          <div class="flex-1 py-[14px] px-[16px]">按照{{ form.remuneration
          }}元/分，发放科研酬金</div>
        </div>
      </div>
      <div class="flex">
        <div class="flex-1 flex items-center">
          <div class="flex items-center w-[131px] h-full px-[16px] text-[#4E5969] bg-[#F6FAFF] border-r-[1px] border-[#BEDAFF]">管理文件
          </div>
          <div class="flex flex-col  flex-1 py-[14px] px-[16px]">
            <FilePreviewItem v-for="file in form.files" :key="file.id" :file="file" />
          </div>
        </div>
      </div>
    </div>
    <TitleBar title="科研工作量化计分标准">
      <div v-if="type !== 'view'">
        <el-button link type="primary" v-loading="copyLoading" @click="handleCopy">沿用前次标准</el-button>
        <el-button type="primary" @click="handleEdit('', 'add')">新增</el-button>
      </div>
    </TitleBar>
    <el-table v-loading="tableLoading" :data="tableData" border>
      <el-table-column prop="key" label="序号" width="48">
        <template #default="{ $index }">
          <div>{{ $index + 1 }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="typeName" label="类别" min-width="200" />
      <el-table-column prop="name" label="量化指标" min-width="300" />
      <el-table-column prop="type" label="计算方式" min-width="100">
        <template #default="{ row }">
          <div>{{ calculationMethodMap[row.type as keyof typeof calculationMethodMap] }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" min-width="180">
        <template #default="{ row }">
          <div>{{ row.unitName ? row.unitName : row.type === 5 ? '-' : `每${row.unit}${unitEnumMap[row.unitEnum as keyof
            typeof
            unitEnumMap]}` }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="mark" label="分值" min-width="200">
        <template #default="{ row }">
          <div>{{ row.type === 5 ? '-' : row.mark }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row.id, 'view')">查看</el-button>
          <el-button v-if="type !== 'view'" link type="primary" @click="handleEdit(row.id, 'edit')">编辑</el-button>
          <el-button v-if="type !== 'view'" link type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="status === 1" class="h-[72px]">

    </div>
    <EditModal v-if="editVisible" :visible="editVisible" :id="currentId" :assessment-method-id="id"
      :type="calculationType" @cancel="handleCancel" />

    <!-- 沿用前次标准确认框 -->
    <DelConfirmModal v-if="copyVisible" :visible="copyVisible" :loading="copyLoading" text='是否确认使用上一次已生效的计分标准？'
      tip="使用后将覆盖当前方案在的计分标准。" ok-text="确认" ok-type="primary" @cancel="copyVisible = false" @ok="copy" />

    <DelConfirmModal v-if="delVisible" :visible="delVisible" :loading="delLoading" @cancel="delVisible = false"
      @ok="deleteCalculation({ id: currentId })" />
    <div v-if="status === 1 || type === 'add'" class="footer">
      <el-button v-if="type === 'view'" type="primary" @click="type = 'edit'">编辑</el-button>
      <el-button v-else v-loading="addLoading || updateLoading" type="primary" @click="handleSubmit">保存</el-button>
    </div>
  </div>
</template>

<script setup lang="ts" name="ManagerWayDetail">
import formateDate from '@/utils/formateDate'
import { ElMessage } from 'element-plus'
import TitleBar from '../components/TitleBar.vue';
import EditModal from './components/EditModal.vue'
import { calculationMethodMap, unitEnumMap } from '@/utils/constText'
import {
  assessmentMethodDetail,
  assessmentMethodListAssessmentCalculation,
  assessmentMethodCopy,
  assessmentMethodDeletedAssessmentCalculation,
  assessmentMethodCreate,
  assessmentMethodUpdate
} from '@/api/assessment';
import {
  AssessmentMethodCalculationListRespVO,
  AssessmentMethodDetailRespVO,
  BaseSuccessRespDTO
} from '@/api/assessment/types';


const route = useRoute()
const query = computed(() => route.query || {})

const id = ref('')
const type = ref('')
const status = ref<Number>(0)

const formRef = ref()
const form = ref({
  name: '',
  documentName: '',
  effectiveTime: '',
  remuneration: 0,
  files: []
})

const rules = {
  name: [{ required: true, message: "管理办法名称不能为空", trigger: "blur" }],
  documentName: [{ required: true, message: "文号不能为空", trigger: "blur" }],
  effectiveTime: [{ required: true, message: "开始生效时间不能为空", trigger: "blur" }],
  remuneration: [{ required: true, message: "科研分酬金标准不能为空", trigger: "blur" }],
  files: [{ required: true, message: "管理文件不能为空", trigger: "blur", type: 'array' }],
}

const tableData = ref<AssessmentMethodCalculationListRespVO[]>([])

const currentId = ref('')
const delVisible = ref(false)
const editVisible = ref(false)
const calculationType = ref('')
const copyVisible = ref(false)
const isCopy = ref(false)
const isCreate = ref(false)

const { run: getDetail } = useRequest(() => assessmentMethodDetail({ id: id.value }), {
  manual: true,
  onSuccess: (res: AssessmentMethodDetailRespVO) => {
    status.value = res?.status
    form.value = {
      name: res?.name as string,
      documentName: res?.documentName as string,
      effectiveTime: res?.effectiveTime as string,
      remuneration: res?.remuneration as number,
      files: res?.fileList || []
    }
  }
})

const { run: getData, loading: tableLoading } = useRequest(() => assessmentMethodListAssessmentCalculation({
  assessmentMethodId: id.value
}), {
  manual: true,
  onSuccess: (res: AssessmentMethodCalculationListRespVO[]) => {
    tableData.value = res || []
  }
})

const { run: copy, loading: copyLoading } = useRequest(() => assessmentMethodCopy({ id: id.value }), {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res?.isSuccess) {
      copyVisible.value = false
      isCopy.value = false
      ElMessage({
        message: '沿用成功!',
        type: 'success',
        plain: true,
      })
    }
    getData()
  }
})

const { run: update, loading: updateLoading } = useRequest(() => assessmentMethodUpdate({
  id: id.value,
  name: form.value.name,
  documentName: form.value.documentName,
  effectiveTime: formateDate(form.value.effectiveTime).format('YYYY-MM-DD'),
  remuneration: form.value.remuneration,
  file: form.value.files?.map(file => file.id) || []
}), {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res?.isSuccess) {
      ElMessage({
        message: '基本信息保存成功!',
        type: 'success',
        plain: true,
      })
      getData()
    }
  }
})

const { run: create, loading: addLoading } = useRequest(() => assessmentMethodCreate({
  name: form.value.name,
  documentName: form.value.documentName,
  effectiveTime: formateDate(form.value.effectiveTime).format('YYYY-MM-DD'),
  remuneration: form.value.remuneration,
  file: form.value.files?.map(file => file.id) || []
}), {
  manual: true,
  onSuccess: (res: string) => {
    if (res) {
      id.value = res
      ElMessage({
        message: '基本信息保存成功!',
        type: 'success',
        plain: true,
      })
      if (isCopy.value) {
        copyVisible.value = true
      } else if (isCreate.value) {
        editVisible.value = true
      }
    }
  }
})

const { run: deleteCalculation, loading: delLoading } = useRequest(assessmentMethodDeletedAssessmentCalculation, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res?.isSuccess) {
      delVisible.value = false
      ElMessage({
        message: '删除成功!',
        type: 'success',
        plain: true,
      })
      getData()
    }
  }
})

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (id.value) {
        update()
      } else {
        create()
      }
    }
  })
}

const handleCopy = () => {
  if (id.value) {
    copyVisible.value = true
  } else {
    formRef.value?.validate(valid => {
      if (valid) {
        isCopy.value = true
        create()
      } else {
        ElMessage({
          message: '请先完善表单数据!',
          type: 'error',
          plain: true,
        })
      }
    })
  }
}

const handleEdit = (calculationId: string, type: string) => {
  currentId.value = calculationId
  calculationType.value = type
  if (type === 'add') {
    if (id.value) {
      editVisible.value = true
    } else {
      formRef.value.validate(valid => {
        if (valid) {
          isCreate.value = true
          create()
        }
      })
    }
  } else {
    editVisible.value = true
  }
}

const handleCancel = (isUpdate: boolean) => {
  editVisible.value = false
  if (isUpdate) {
    getData()
  }
}

const handleDelete = (id: string) => {
  currentId.value = id
  delVisible.value = true
}

watch(() => query.value.id, () => {
  id.value = query.value.id as string
  type.value = query.value.type as string
  if (id.value) {
    getDetail()
    getData()
  }
}, { immediate: true })
</script>

<style scoped lang="scss">
.manager-way-detail {
  --at-apply: min-h-full p-[20px] bg-white rounded-[4px];
}

.footer {
  --at-apply: fixed bottom-0 left-0 w-full h-[72px] leading-[72px] text-center border-t-solid border-t-[1px] border-[#E5E6EB] bg-white z-[100];
}
</style>